<?php

class Layout {

	private $CI;
	public $output_type = 'wrapper';
	public $data = array(
			'js_files' => array()
		,	'js_code'  => array()
		,	'js_vars'  => array()
	);
	public $css = array('skin/default/style.css');

	/**
	 *  Constructor
	 */
	public function __construct()
	{
		$this->CI =& get_instance();
	}

	// Redirect during same request
	public function redirect($module, $output_type='array')
	{
		$this->data['url'] = site_url($this->CI->store->data('vars', 'index') == $module ? '' : $module);
		$method = 'index';
		if(($pos = strrpos($module, '/')) != FALSE) {
			$method = substr($module, $pos + 1);
			$module = substr($module, 0, $pos);
		}

		if($class = modules::load($module)) {

			if (method_exists($class, $method))	{
				ob_start();
				$args = func_get_args();
				call_user_func_array(array($class, $method), array_slice($args, 1));
				$buffer = ob_get_clean();

				$output = call_user_func_array(array($class, 'render'), array($buffer, $output_type, true));

				if($output_type == 'array') {
					foreach($output as $id => $o) {
						$this->data[$id] = $o;
					}

					$this->CI->output->set_output($output['output']);
					return $output['output'];
				} else {
					$this->output_type = '';
					$this->CI->output->set_output($output);
					return $output;
				}
			}

			return false;
		}
	}

	// Add success message to output
	function success_message($msg) {
		$out = $this->CI->output->get_output();
		$out = $this->CI->load->view('misc/success_message', array('msg'=> $msg), true) . $out;
		$this->CI->output->set_output($out);
	}


	// Add JS file to load
	function add_js_file($file) {
		if(strpos($file, "http://") === false) {
			$file = base_url("js/{$file}");
		}
		$this->data['js_files'][] = $file;
	}

	// Add JS var to include
	function add_js_var($id, $val) {
		if(is_array($id)) {
			$var = &$this->data['js_vars'];
			foreach($id as $i) {
				$var = &$var[$i];
			}
			$var = $val;
		} else {
			$this->data['js_var'][$id] = $val;
		}
	}
}